package cn.ac.van.imeigen.controller;

import cn.ac.van.imeigen.utils.FileLoadUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

@RestController
public class ImgGenController {
  @GetMapping("/getMarried")
  public String getMarried() {
    File template;
    Font KAI_GB2312;
    try {
      //初始化字体配置、背景配置
      KAI_GB2312 = Font.createFont(Font.TRUETYPE_FONT, FileLoadUtil.loadFont("kt_gb2312.ttf"));
      KAI_GB2312.deriveFont(Font.TRUETYPE_FONT, 350);
      template = FileLoadUtil.loadBackGround("bg.jpg");
      //初始化画布
      BufferedImage background = resizeImage(1080, 899, ImageIO.read(template));
      Graphics2D g = background.createGraphics();
      g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
      g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
      g.setColor(new Color(0xFF0000));
      g.setFont(KAI_GB2312);
      g.drawString("S", 300, 250);
      g.dispose();

      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      ImageIO.write(background, "jpg", baos);
      byte[] bytes = baos.toByteArray();//转换成字节
      Base64.Encoder encoder = Base64.getEncoder();
      String b64 = encoder.encodeToString(bytes).trim();
      b64 = b64.replaceAll("\n", "").replaceAll("\r", "");
      b64 = "data:image/jpeg;base64," + b64;
      return b64;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }

  public BufferedImage resizeImage(int x, int y, BufferedImage bfi) {
    BufferedImage bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_RGB);
    bufferedImage.getGraphics().drawImage(
      bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
    return bufferedImage;
  }
}
